package com.dindang.maintenance.mvp.presenter;

import android.app.Application;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.dindang.maintenance.R;
import com.dindang.maintenance.mvp.contract.MaintainManagementContract;
import com.dindang.maintenance.mvp.model.CommontCons;
import com.dindang.maintenance.mvp.model.entity.BaseResponse;
import com.dindang.maintenance.mvp.model.entity.Build;
import com.dindang.maintenance.mvp.model.entity.MaintainFiltrate;
import com.dindang.maintenance.mvp.model.entity.Repair;
import com.dindang.maintenance.mvp.ui.activity.MaintainDetailsActivity;
import com.dindang.maintenance.mvp.ui.adapter.multitype.MaintainViewAdapter;
import com.dindang.maintenance.mvp.ui.widget.AdvanceSearchDialog;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.longxi.gamer_base.BaseAppConst;
import com.longxi.gamer_base.MyApplication;
import com.longxi.gamer_base.dialog.WaitDialog;
import com.longxi.gamer_base.model.MaintainDetailsEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import in.srain.cube.views.ptr2.PtrDefaultHandler2;
import in.srain.cube.views.ptr2.PtrFrameLayout;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


@ActivityScope
public class MaintainManagementPresenter extends BasePresenter<MaintainManagementContract.Model, MaintainManagementContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private WaitDialog mWaitDialog;
//    private List<Maintain> mList = new ArrayList<>();
    private MaintainViewAdapter mAdapter;
    private Repair.RepairListParam mParam = new Repair.RepairListParam();
    private Build.BuildParam mBuildParam = new Build.BuildParam();

    List<MaintainFiltrate.Item> mBuildList = new ArrayList<>();
    private List<Repair.RepairList.RowsBean> mList = new ArrayList<>();
    private int LIMIT = 10;
    private int START = 1;
    @Inject
    public MaintainManagementPresenter(MaintainManagementContract.Model model, MaintainManagementContract.View rootView) {
        super(model, rootView);
    }

    public void init() {
        mWaitDialog = new WaitDialog(mRootView.getActivity());
        EventBus.getDefault().register(this);
        initListener();
        initAdapter();
        queryPageList();
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void MaintainDetailsRefresh(MaintainDetailsEvent maintainDetailsEvent){
        queryPageList();
    }

    private void initListener() {
        mRootView.getPtrclassicframelayout().setMode(PtrFrameLayout.Mode.REFRESH);
        mRootView.getPtrclassicframelayout().disableWhenHorizontalMove(true);
        mRootView.getPtrclassicframelayout().setLastUpdateTimeRelateObject(this);
        mRootView.getPtrclassicframelayout().setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                queryPageList();
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                mParam.page = START;
                queryPageList();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return super.checkCanDoRefresh(frame, content, header);
            }

            @Override
            public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
                return super.checkCanDoLoadMore(frame, content, footer);
            }
        });

        mRootView.getEtSearch().setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId == EditorInfo.IME_ACTION_SEARCH){
                    mParam.likeValue = mRootView.getEtSearch().getText().toString().trim();
                    mParam.page = START;
                    queryPageList();
                    mRootView.getEtSearch().clearFocus();
                    InputMethodManager imm = (InputMethodManager) mRootView.getActivity().getSystemService(mRootView.getActivity().INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(mRootView.getEtSearch().getWindowToken(), 0);
                }
                return false;
            }
        });
    }

    private void initAdapter() {
//        for (int i = 1; i <= 10; i++) {
//            mList.add(new Maintain());
//        }
        mAdapter = new MaintainViewAdapter(mList,
            new MaintainViewAdapter.OnClickListener() {
                @Override
                public void onClick(int position) {
                    Intent intent = new Intent(mRootView.getActivity(), MaintainDetailsActivity.class);
                    intent.putExtra("id",mList.get(position).getL_id()+"");
                    mRootView.getActivity().startActivity(intent);
                }
            });
        mRootView.getRecyclerview().setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
    }

    private void queryPageList() {
        mParam.corpId = BaseAppConst.accountInfo.getCorpId();
        mParam.page = START;
        mParam.rows = LIMIT;
        mParam.userId = BaseAppConst.accountInfo.getUserId();
//        mParam.cFrom = "2";
        mModel.queryPageList(mParam)
        .subscribeOn(Schedulers.io())
        .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
        .doOnSubscribe(disposable -> {

        }).subscribeOn(AndroidSchedulers.mainThread())
        .observeOn(AndroidSchedulers.mainThread())
        .doFinally(() -> {
//            mRootView.getEmptyLayout().setEmptyStatus(mRootView.getEmptyLayout().STATUS_ERROR);
            if(mRootView.getPtrclassicframelayout().isRefreshing()){
                mRootView.getPtrclassicframelayout().refreshComplete();
            }
        })
        .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
        .subscribe(new ErrorHandleSubscriber<BaseResponse<Repair.RepairList>>(mErrorHandler) {
            @Override
            public void onNext(BaseResponse<Repair.RepairList> response) {
                if(response.getStatus().equals(BaseAppConst.OUT_TOKEN)){
                    MyApplication.getInstance().gotoLoginActivity();
                }
                if(!response.isSuccess()){
                    ArmsUtils.makeText(mApplication, response.getStatuMsg());
                    return;
                }
                if(mRootView.getPtrclassicframelayout().isRefreshing()){
                    mRootView.getPtrclassicframelayout().refreshComplete();
                }
                if(response.getData().getRows().size() < LIMIT){
                    mRootView.getPtrclassicframelayout().setMode(PtrFrameLayout.Mode.REFRESH);
                }else{
                    mRootView.getPtrclassicframelayout().setMode(PtrFrameLayout.Mode.BOTH);
                    mParam.page++;
                }
                if(mParam.page == START){
                    mList.clear();
                }
                mList.addAll(response.getData().getRows());
                if(mList.size() == 0){
                    mRootView.getEmptyLayout().setEmptyStatus(mRootView.getEmptyLayout().STATUS_NO_DATA);
                }else{
                    mRootView.getEmptyLayout().hide();
                }
                mAdapter.notifyDataSetChanged();
            }
        });
    }

    private AdvanceSearchDialog.Builder mAdvanceSearchDialog;
    /**
     * 高级搜索弹框
     */
    public void dialogAdvanceSearch(){
        if(mAdvanceSearchDialog != null){
            mAdvanceSearchDialog.show();
        }else{
            mAdvanceSearchDialog = new AdvanceSearchDialog.Builder(mRootView.getRecyclerview().getContext());
            mAdvanceSearchDialog.setListener(new AdvanceSearchDialog.OnClickListener() {
                @Override
                public void onSearch(List<MaintainFiltrate.Category> categorys) {
                    StringBuffer string = new StringBuffer();
                    for (MaintainFiltrate.Category c : categorys)
                        string.append(c.name + ":" + c.value + "\n");
                    mParam.applyArea = "";
                    for (int i = 1; i < categorys.get(0).item.size(); i++) {
                        // 1：私有区域，2：公共区域
                        if(categorys.get(0).item.get(i).isSelect){
                            mParam.applyArea = categorys.get(0).item.get(i).id+"";
                        }
                    }
                    mParam.status = "";
                    for (int i = 1; i < categorys.get(1).item.size(); i++) {
                        if(categorys.get(1).item.get(i).isSelect){
                            mParam.status=CommontCons.states_num[categorys.get(1).id];
                        }
                    }
                    mParam.createDateStart = "";
                    mParam.createDateEnd = "";
                    if(categorys.get(2).item.get(1).isSelect){
                        if(!categorys.get(2).item.get(1).startValue.contains("请选择")){
                            mParam.createDateStart = categorys.get(2).item.get(1).startValue.replace("年","-").replace("月","-").replace("时",":").replace("日","").replace("分","");
                        }
                        if(!categorys.get(2).item.get(1).endValue.contains("请选择")){
                            mParam.createDateEnd = categorys.get(2).item.get(1).endValue.replace("年","-").replace("月","-").replace("时",":").replace("日","").replace("分","");
                        }
                    }
                    mParam.bid = "";
                    if(categorys.get(3)!=null&&categorys.get(3).item!=null){
                        for (int i = 1; i < categorys.get(3).item.size(); i++) {
                            if(categorys.get(3).item.get(i).isSelect){
                                mParam.bid = categorys.get(3).item.get(i).id+"";
                            }
                        }
                    }
                    mParam.page = START;
                    queryPageList();
//                    ArmsUtils.makeText(mApplication, string.toString());
                    mAdvanceSearchDialog.dismiss();
                }

                @Override
                public void onRequestData(MaintainFiltrate.Category category) {
                    switch (category.url) {
                        case "findBuilding":
                            if(category.item.size() == 0){
                                findBuilding(category);
                            }
                            break;
                        default:
                            break;
                    }
                }
            })
            .create()
            .show();
        }
    }

    /**
     * 查询权限小区
     */
    private void findBuilding(MaintainFiltrate.Category category){
        mWaitDialog.showWaitingDialog(ArmsUtils.getString(mApplication, R.string.data_load));
        mBuildParam.setcId(BaseAppConst.accountInfo.getUserId()+"");
        mBuildParam.setIsAdmin(BaseAppConst.accountInfo.getIsAdmin());
        mBuildParam.setCorpid(BaseAppConst.accountInfo.getCorpId());
        mModel.findBuilding(mBuildParam)
        .subscribeOn(Schedulers.io())
        .retryWhen(new RetryWithDelay(0, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
        .doOnSubscribe(disposable -> {

        }).subscribeOn(AndroidSchedulers.mainThread())
        .observeOn(AndroidSchedulers.mainThread())
        .doFinally(() -> {
            mWaitDialog.hideWaitingDialog();
        })
        .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
        .subscribe(new ErrorHandleSubscriber<BaseResponse<List<Build.Building>>>(mErrorHandler) {
            @Override
            public void onNext(BaseResponse<List<Build.Building>> response) {
                if(response.getStatus().equals(BaseAppConst.OUT_TOKEN)){
                    MyApplication.getInstance().gotoLoginActivity();
                }
                if(!response.isSuccess()){
                    ArmsUtils.makeText(mApplication, response.getStatuMsg());
                    return;
                }

                mBuildList.clear();
                mBuildList.add(new MaintainFiltrate.Item(0, "全部", true));
                for (Build.Building building : response.getData()) {
                    mBuildList.add(new MaintainFiltrate.Item(building.id, building.name, false));
                }

                category.item.addAll(mBuildList);
                mAdvanceSearchDialog.refreshCategoryAndItem();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;

        this.mList = null;
        this.mAdapter = null;
        if(this.mAdvanceSearchDialog != null){
            this.mAdvanceSearchDialog.onDestroy();
            this.mAdvanceSearchDialog = null;
        }

        this.mBuildParam = null;
        this.mBuildList = null;
        this.mWaitDialog = null;
    }

}
